package icom.acm.dwr;

import icom.acm.util.StaticData;
import icom.acm.util.json.JSONMsg;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

public class MessageDWR {
	public MessageDWR(){}
	
	public String getTest(){
		WebContext wctx = WebContextFactory.get();
        String currentPage = wctx.getCurrentPage();
        System.out.println(currentPage);
		System.out.println("Hello, MessageDWR!");
		return "Hello, MessageDWR!";
	}		
	
	public String send(String ids){
		System.out.println("send:"+ids);
		JSONMsg jmsg = new JSONMsg(true, "");
		
		ScriptBuffer script = new ScriptBuffer();
    	script.appendScript("receiveMessage(")
        .appendData(jmsg.toString())
        .appendScript(");");			
        
        String[] sessionids = ids.split(",");
        for (int i=0,len=sessionids.length;i<len;i++){
        	String sessionid = sessionids[i];
        	ScriptSession scriptSession = null;
        	
        	try {
        		scriptSession = StaticData.SESSIONID_SCRIPTSESSION_MAP.get(sessionid);
        	} catch (Exception ex){
        		ex.printStackTrace();
        		continue;
        	}
        	if (scriptSession == null) continue;
        	
        	scriptSession.addScript(script);
        }
		                		
		return ids;
	}
}
